package TCP.Communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Grup:Communication
 * @Auther:cola
 * @Data:2021/4/1-2021-04-23:05
 * @version:1.0
 */
public class Server {
    public static void main(String[] args) {
        //保护客户端处理的线程
        Vector<UserThread> vector = new Vector<>();
        ExecutorService es = Executors.newFixedThreadPool(5);
        System.out.println("服务器已启动,正在等待客户端的连接!");
        //创建服务器的socket
        try {
            ServerSocket server = new ServerSocket(8888);
            while (true) {
                Socket socket = server.accept();
                UserThread user = new UserThread(socket, vector);
                es.execute(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class UserThread implements Runnable {
    private Socket socket;
    Vector<UserThread> vector;//客户端处理线程的集合
    private String name;//客户端的用户名称(唯一)
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private boolean flag = true;

    public UserThread() {
    }

    public UserThread(Socket socket, Vector<UserThread> vector) {
        this.socket = socket;
        this.vector = vector;
        vector.add(this);
    }

    @Override
    public void run() {
        try {
            System.out.println("客户端" + socket.getInetAddress().getHostAddress() + "已连接");
            ois = new ObjectInputStream(socket.getInputStream());
            oos = new ObjectOutputStream(socket.getOutputStream());

            while (flag) {
                Message msg = (Message) ois.readObject();
                int type = msg.getType();
                switch (type) {
                    case MessageType.TYPE_SEND:
                        String to = msg.getTo();
                        UserThread ut;
                        int size = vector.size();
                        for (int i = 0; i < size; i++) {
                            ut = vector.get(i);
                            if (to.equals(ut.name) && ut != this) {
                                ut.oos.writeObject(msg);
                                ut.oos.flush();
                                break;
                            }
                        }
                        break;

                    case MessageType.TYPE_LOGIN:
                        name = msg.getFrom();
                        msg.setInfo("欢迎你:");
                        oos.writeObject(msg);
                        break;
                }
            }
            ois.close();
            oos.close();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }
}
